'use strict';

const uuid = require('uuid');

const common = {
    isEmpty: (input) => {
        return input === null || input === undefined || input === '' || JSON.stringify(input) === '{}';
    },

    /**
     * @param {String} prefix 
     * @return {String}
     */
     generateUUID: (prefix=null) => {
        let uuidStr = uuid.v1();
        uuidStr = uuidStr.replace(/-/g, ''); 
        if (prefix != null) {
            uuidStr = prefix + uuidStr;
        }
        return uuidStr;
    },

    /**
     * @getAuthorization
     * @desc 获取请求 authorization
     * @param {Object} req - 请求
     */
    getAuthorization: (req) => {
        let authorization = req.headers.authorization ? req.headers.authorization : req.headers.Authorization;
        return String(authorization || '').split(' ').pop();
    },

    /**
     * @getClientIP
     * @desc 获取用户 ip 地址
     * @param {Object} req - 请求
     */
    getClientIP: (req) => {
        return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
            req.connection.remoteAddress || // 判断 connection 的远程 IP
            req.socket.remoteAddress || // 判断后端的 socket 的 IP
            req.connection.socket.remoteAddress;
    }
};

module.exports = common;
